package com.servlet.form;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.listener.ContextListener;
import com.servlet.model.database.BaseAcces;
import com.servlet.security.MD5;

public class LoginForm extends HttpServlet
{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		boolean correct = false;
		
		HttpSession session = request.getSession();
		//BaseAcces base = (BaseAcces) this.config.getServletContext().getAttribute("base");
		
		BaseAcces base = ContextListener.base;

		String email = request.getParameter("email");
		String motDePasse = request.getParameter("motDePasse");
		String checked = request.getParameter("resterConnecte");

		
		String resultat = null;

		if( email != null && email != "" && motDePasse != null && motDePasse != "")
		{
			motDePasse = MD5.generateCode(motDePasse);

			if( base.verifyAccount(email, motDePasse ) )
			{
				correct = true;
			}
			else
			{
				resultat = "l'email et/ou le mot de passe sont erronés";
			}
		}
		else
		{
			resultat = "vous devez entrer votre email et votre mot de passe";
		}
		
		if( correct )
		{
			System.out.println("Ouverture du compte : " + email + " " + motDePasse );
			
			session.setAttribute("email", email );
			

			if (checked != null) {
				int time = 60*60*24*15;
				String host = request.getServerName();
				Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME", email); // 保存用户名到Cookie
				cookie.setPath("/");
				cookie.setDomain(host);
				cookie.setMaxAge(time);
				response.addCookie(cookie);

				cookie = new Cookie("SESSION_LOGIN_PASSWORD", motDePasse);
				cookie.setPath("/");
				cookie.setDomain(host);
				cookie.setMaxAge(time);
				response.addCookie(cookie);

			}
			
			response.sendRedirect("news");
		}
		else
		{
			System.out.println(resultat);
			
			session.setAttribute("resultat", "La connexion a échoué : " + resultat );
			
			response.sendRedirect("login");
		}
	}
}
